<template>
  <el-dialog ref="dialogRef" class="c-dialog-fixed" v-model="visible" width="500px" @closed="handleClosed"
    @close="handleClose" :title="title" v-loading="loading" :before-close="handleBeforeClose">
    <el-form ref="formRef" :model="data" label-width="auto" :rules="rules" @keyup.enter="save">
      <el-divider>接口信息</el-divider>
      <el-form-item label="接口名称" prop="name">
        <el-input v-model="data.name" placeholder="填写接口名称"></el-input>
      </el-form-item>
      <el-form-item label="接口路径" prop="path">
        <el-input v-model="data.path" placeholder="填写接口完整路径，不区分大小写"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="save" :loading="loading">保存</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import api from "@/api/sys/api";
import { cloneObjectValue, cloneDeepObject } from "@/utils/common";
import { ref, useTemplateRef } from "vue";
import { ElFormItem, ElMessage } from "element-plus";
defineProps({
  inDialog: {
    type: Boolean,
    default: false
  }
})
const openCreate = () => {
  title.value = "创建用户"
  visible.value = true
}

const emit = defineEmits(["close-saved"])
const formRef = useTemplateRef("formRef")
const data = ref({
  id: 0,
  name: "",
  path: ""
})
const initData = cloneDeepObject(data.value)
const loading = ref(false)
const visible = ref(false)
const title = ref("")
const saved = ref(false)

const rules = ref({
  name: [
    { required: true, message: "请填写接口名称" },
    {
      validator: async (rule, value, callback) => {
        const res = await api.checkExistByName(value, data.value.id);
        if (res.data) {
          callback("接口名称已重复");
        } else {
          callback();
        }
      }, trigger: "blur"
    }    
  ],
  path: [
    { required: true, message: "请填写接口路径" },
    {
      validator: async (rule, value, callback) => {
        const res = await api.checkExistByPath(value, data.value.id);
        if (res.data) {
          callback("接口路径已重复");
        } else {
          callback();
        }
      }, trigger: "blur"
    }     
  ]
})



const openEdit = (inputData) => {
  title.value = "编辑接口"
  visible.value = true
  cloneObjectValue(data.value, inputData)
}
const save = async () => {
  loading.value = true
  try {
    await formRef.value.validate();
  }
  catch {
    loading.value = false;
    return;
  }
  let res = await api.save(data.value);
  if (res.code != 0) {
    loading.value = false;
    return;
  }
  ElMessage.success("保存成功");
  data.id = res.data;
  saved.value = true;
  loading.value = false;
}
const handleClosed = () => {
  title.value = "";
  saved.value = false;
  formRef.value.resetFields();
  cloneObjectValue(data.value, initData)
}
const handleClose = () => {
  if (saved.value) {
    emit("close-saved");
  }
}
const handleBeforeClose = (done) => {
  if (loading.value) {
    ElMessage.warning("加载中，请稍候")
    return;
  }
  done()
}
defineExpose({
  openCreate,
  openEdit
})
</script>